package com.bigknow.appstore.proxy.handler.register;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.entity.ProxyResourceMeta;
import com.bigknow.appstore.proxy.handler.base.BaseInboundHandler;
import com.bigknow.appstore.proxy.handler.statistics.SucceedStatisticsHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.timetask.impl.LastRequestVoRemoveWorker;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import com.bigknow.appstore.proxy.util.UriAndUrlHelper;
import com.bigknow.appstore.proxy.vo.RequestVo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpRequest;

import java.net.InetSocketAddress;
import java.util.Date;

/**
 * 如果uri ，user register handler都没有成功构建requestVo
 * 那么此方法将最后调用并保存的requetVo设置为当前请求
 * Created by chaos on 2016/9/19.
 */
@ChannelHandler.Sharable
public class FindLastRequestHandler extends BaseInboundHandler {

    public FindLastRequestHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void read(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {
        if (HandlerVariables.currentRequestVoLocal.get().isErrorCall()) {
            String id = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
            FullHttpRequest request = (FullHttpRequest) msg;
            if (HandlerVariables.lastRequestVos.containsKey(id)) {
                RequestVo requestVo = HandlerVariables.lastRequestVos.get(id);
                requestVo.setCallUri(requestVo.getResourceMeta().getProxyUri()
                        + UriAndUrlHelper.getCorrectUri(requestVo.getResourceMeta().getProxyResName(), request.uri()));
                requestVo.setPrefixUri(requestVo.getResourceMeta().getProxyUri());
                requestVo.setSuffixUri(UriAndUrlHelper.getCorrectUri(requestVo.getResourceMeta().getProxyResName(), request.uri()));
                requestVo.setCallTime(new Date());
                requestVo.setCallIp(((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress());
                //userId
                requestVo.setUserId(HandlerVariables.currentRequestVoLocal.get().getUserId());
                HandlerVariables.currentRequestVoLocal.set(requestVo);
                ((LastRequestVoRemoveWorker) proxyServer.getTimeWorkerMap().get(LastRequestVoRemoveWorker.class.getName()))
                        .addLastRequestTime(id);
                //将requestVo改为不是ErrorCall
                requestVo.setErrorCall(false);
            }
        }
        ctx.fireChannelRead(msg);
    }

}
